package com.hzit.manager.handler;

import com.alibaba.csp.sentinel.adapter.servlet.CommonFilter;
import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.adapter.servlet.callback.WebCallbackManager;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.ruoyi.common.core.domain.R;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.Filter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 类名：
 * 作者：WF
 * 功能：定制限流异常的提示信息(方案一)
 * 注意：此种方案需要下面两步操作（包含注册过滤器）
 */
@Configuration
public class MyResourceHandler  {

	@PostConstruct
	public void init(){
		UrlBlockHandler urlBlockHandler = new UrlBlockHandler() {
			@Override
			public void blocked(HttpServletRequest httpServletRequest, HttpServletResponse response, BlockException e) throws IOException {
				R<Object> r = R.fail(HttpStatus.INTERNAL_SERVER_ERROR.value(), "出现了限流错误！");
				response.setContentType("application/json;charset=utf8");
				response.getWriter().println(JSON.toJSONString(r));
				response.getWriter().flush();
			}
		};
		WebCallbackManager.setUrlBlockHandler(urlBlockHandler);
	}

	@Bean
	public FilterRegistrationBean sentinelFilterRegistration() {
		FilterRegistrationBean<Filter> registration = new FilterRegistrationBean<>();
		registration.setFilter(new CommonFilter());
		registration.addUrlPatterns("/*");
		registration.addInitParameter(CommonFilter.WEB_CONTEXT_UNIFY, "false");
		registration.setName("sentinelFilter");
		registration.setOrder(1);

		return registration;
	}

}
